<?php
namespace Destroyer\Models;

use BaconQrCode\Renderer\Color\Rgb;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\Fill;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;

use PragmaRX\Google2FA\Google2FA;


/**
 * 双因素认证
 * 业务逻辑
 * 启用时设置two_factor_secret、two_factor_recovery_codes
 * 关闭时三个字段设为null
 * 
 * 启用 
 * 取消
 * 禁用 
 * 确认
 * 
 * two_factor_secret和two_factor_confirmed_at均设置时视为真实启用
 * 
 */
trait TwoFactorAuthenticatable
{

	// 确定是否启用了双重验证
    public function hasEnabledTwoFactorAuthentication()
    {
        return ! is_null($this->two_factor_secret) &&
               ! is_null($this->two_factor_confirmed_at);
    }

    // 获取用户的双因子认证恢复码。
    public function recoveryCodes()
    {
        return json_decode(decrypt($this->two_factor_recovery_codes), true);
    }

    // 将给定的恢复代码替换为用户存储代码中的新代码。
    public function replaceRecoveryCode($code)
    {

    }

    // 获取用户双因子认证二维码SVG
   	public function twoFactorQrCodeSvg()
    {
        $svg = (new Writer(
            new ImageRenderer(
                new RendererStyle(192, 0, null, null, Fill::uniformColor(new Rgb(255, 255, 255), new Rgb(45, 55, 72))),
                new SvgImageBackEnd
            )
        ))->writeString($this->twoFactorQrCodeUrl());

        return trim(substr($svg, strpos($svg, "\n") + 1));
    }

    // 获取双因子认证二维码URL(二维码内容)
    public function twoFactorQrCodeUrl()
    {
        $google2fa = new Google2FA();
        return $google2fa->getQRCodeUrl(config('app.name'), 'email', $this->two_factor_secret);
    }
}